import pymysql
from common.constant import *
from loguru import logger
from dbutils.pooled_db import PooledDB
from pymysql import converters, FIELD_TYPE

class CursorHandler:

    def __init__(self):
        #打开数据库连接
        try:
            conv = converters.conversions
            conv[FIELD_TYPE.NEWDECIMAL] = float
            self.db = PooledDB(pymysql,
                host=mysql_ip,  # 服务端地址
                port=mysql_port,  # 服务端端口
                maxconnections=50,
                mincached=30,
                user=mysql_user,  # 用户名
                password=mysql_password,  # 密码
                database=mysql_database,  # 要连接的数据库
                charset='utf8',  # 设置数据库编码
                cursorclass=pymysql.cursors.DictCursor, # 以字典的方式返回结果
                conv=conv # 数据类型转换
                               ).connection()
        except Exception:
            print('mysql connect error')
            logger.error('mysql connect error')
        self.make_cursor()

    def make_cursor(self):
        try:
            # 构造游标
            self.cursor = self.db.cursor()
        except IOError:
            print('msyql_cursor make error')
            logger.error('msyql_cursor make error')
            self.make_cursor()
        except Exception:
            print('mysql other error')
            logger.error('mysql other error')
            self.make_cursor()
        return self.cursor

    def close_database(self):
        # 关闭数据库连接
        self.db.close()

    def search_with_condition(self, sql, condition):
        # 待查询条件的搜索
        sql.format(*condition)
        self.cursor.execute(sql)
        return self.cursor.fetchall()

    def search_alone(self, sql=''):
        # 查询数据库的执行语句
        # sql = 'select * from zt_acl limit 10'
        try:
            # self.make_cursor()
            self.cursor.execute(sql)
            self.cursor.close()
        except Exception as e:
            print(e)
            self.__init__()
            self.cursor.execute(sql)
        return self.cursor.fetchall()

cursor = CursorHandler()
